<template>
  <div class="project-application">
    <!-- 申请人信息 -->
    <el-card class="section-card">
      <div slot="header">
        <span>申请人信息</span>
      </div>
      <el-form :model="applicantInfo" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="申请人姓名">
              <el-input v-model="applicantInfo.applicationName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人编号">
              <el-input v-model="applicantInfo.applicationCode" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请日期">
              <el-date-picker v-model="applicantInfo.applyDate" type="date"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 客户信息 -->
    <el-card class="section-card">
      <div slot="header" class="customer-header">
        <span>客户信息</span>
        <el-button type="primary" size="small" @click="selectCustomer">选择客户</el-button>
      </div>
      <el-form :model="customerInfo" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="客户代码">
              <el-input v-model="customerInfo.code" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input v-model="customerInfo.customerName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input v-model="customerInfo.contactPerson" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input v-model="customerInfo.contactPhone" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="客户地址">
              <el-input v-model="customerInfo.region" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 项目信息 -->
    <el-card class="section-card" v-if="customerInfo.code">
      <div slot="header" class="project-header">
        <span>项目信息</span>
        <el-button type="primary" size="small" @click="addProject">添加项目</el-button>
      </div>
      
      <!-- 项目列表为空时显示提示信息 -->
      <template v-if="projectList.length === 0">
        <div class="empty-project">
          <el-empty description="暂无项目信息"></el-empty>
        </div>
      </template>

      <!-- 有项目数据显示项目列表 -->
      <template v-else>
        <div v-for="(project, index) in projectList" :key="index" class="project-item">
          <el-divider v-if="index > 0">项目 {{ index + 1 }}</el-divider>
          <el-form :model="project" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="项目名称">
                  <el-input v-model="project.projectName" :disabled="!project.isNew"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目类型">
                  <el-select v-model="project.projectType" placeholder="请选择" :disabled="!project.isNew">
                    <el-option label="一次研发" value="1"></el-option>
                    <el-option label="二次研发" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="预计成本">
                  <el-input 
                    v-model="project.projectedCost" 
                    type="number"
                    :disabled="!project.isNew"
                    @input="validateBudget1($event, project)"
                    min="0">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="预计售价">
                  <el-input 
                    v-model="project.sellPrice" 
                    type="number"
                    :disabled="!project.isNew"
                    @input="validateBudget2($event, project)"
                    min="0">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="预计盈利">
                  <el-input 
                    v-model="project.projectedProfit" 
                    type="number"
                    :disabled="!project.isNew"
                    @input="validateBudget3($event, project)"
                    min="0">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="产品名称">
                  <el-input v-model="project.productName" :disabled="!project.isNew"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
                 <el-col :span="12">
                <el-form-item label="产品物料">
                  <el-input 
                    type="textarea" 
                    v-model="project.productMaterial" 
                    rows="3"
                    :disabled="!project.isNew">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品描述">
                  <el-input 
                    type="textarea" 
                    v-model="project.productDescription" 
                    rows="3"
                    :disabled="!project.isNew">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="目标客户群体">
                  <el-input v-model="project.targetCustomer" :disabled="!project.isNew"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="目标市场">
                  <el-input v-model="project.targetMarket" :disabled="!project.isNew"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 只有新添加的项目才能删除 -->
            <el-row v-if="project.isNew">
              <el-col :span="24" style="text-align: right;">
                <el-button type="danger" @click="removeProject(index)">删除此项目</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
    </el-card>

    <!-- 提交按钮 -->
    <div class="submit-section" v-if="customerInfo.code">
      <el-button type="primary" @click="submitForm">提交申请</el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>

    <!-- 选择客户对话框 -->
    <el-dialog title="选择客户" :visible.sync="customerDialogVisible" width="70%">
      <el-table
        :data="customerList"
        height="400"
        border
        @row-click="handleCustomerSelect"
      >
        <el-table-column prop="code" label="客户代码"></el-table-column>
        <el-table-column prop="customerName" label="客户名称"></el-table-column>
        <el-table-column prop="contactPerson" label="联系人"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
        <el-table-column prop="region" label="地址"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ProjectApplication',
  data() {
    return {
      // 申请人信息
      applicantInfo: {
        applicationName: 'zf',
        applicationCode: '1',
        applyDate: new Date()
      },
      // 客户信息
      customerInfo: {
      },
      // 查询出的项目列表
      projectList1: [],
      // 新添加的项目列表
      projectList2: [],
      // 客户选择对话框
      customerDialogVisible: false,
      // 客户列表数据
      customerList: [
        // 更多客户数据...
      ],
    }
  },
  computed: {
    // 合并两个项目列表用于显示
    projectList() {
      return [...this.projectList1, ...this.projectList2]
    }
  },
  methods: {
    // 打开选择客户对话框
    selectCustomer() {
      this.customerDialogVisible = true
      // 这里应该调用API获取客户列表
      this.getCustomerList()
    },
    // 获取客户列表
    getCustomerList() {
      // 调用API取客户列表
      // this.customerList = await getCustomers()
      this.$axios.get('api/project-server/application/queryAllCustomer')
      .then(resp => {
        console.log(resp.data)
        if(resp.data.code === 200) {
            this.customerList = resp.data.data
        }
      })
    },
    // 选择客户
    handleCustomerSelect(row) {
      this.customerInfo = { ...row }
      this.customerDialogVisible = false
      this.projectList1 = []
      this.projectList2 = []
      
      // 获取客户相关的项目列表
      this.$axios.get('api/project-server/application/queryProjectListByCode?customerCode=' + row.code)
        .then(resp => {
          console.log('API返回数据:', resp.data)
          if(resp.data.code === 200) {
            // 处理项目类型的显示
            this.projectList1 =  (resp.data.data || []).map(project => {
              // 确保 projectType 是字符串类型
              const projectType = String(project.projectType || '1')
              return {
                ...project,
                isNew: false,
                projectApplicationCode: project.projectApplicationCode || '',
                projectName: project.projectName || '',
                projectType: projectType, // 确保是字符串类型
                projectedCost: project.projectedCost || 0,
                sellPrice: project.sellPrice || 0,
                projectedProfit: project.projectedProfit || 0,
                productName: project.productName || '',
                productMaterial: project.productMaterial || '',
                productDescription: project.productDescription || ''
              }
            })
            // 打印检查转换后的数据
            console.log('转换后的项目列表:', this.projectList1)
          }
        })
        .catch(error => {
          console.error('获取项目列表失败:', error)
          this.$message.error('获取项目列表失败')
        })
    },
    // 添加新项目
    addProject() {
      this.projectList2.push({
        isNew: true,
        projectName: '',
        projectType: '1',
        projectedCost: 0,
        sellPrice: 0,
        projectedProfit: 0,
        productName: '',
        productMaterial: '',
        productDescription: ''
      })
    },
    // 删除项目
    removeProject(index) {
      // 计算实际的索引位置
      const totalIndex = index
      const list1Length = this.projectList1.length
      
      if (totalIndex >= list1Length) {
        // 如果是新添加的项目，从 projectList2 中删除
        this.projectList2.splice(totalIndex - list1Length, 1)
      }
    },
    validateBudget1(value, project) {
      if (value < 0) {
        project.projectedCost = 0
        this.$message.warning('金额不能小于0')
      }
    },
    validateBudget2(value, project) {
      if (value < 0) {
        project.sellPrice = 0
        this.$message.warning('金额不能小于0')
      }
    },
    validateBudget3(value, project) {
      if (value < 0) {
        project.projectedProfit = 0
        this.$message.warning('金额不能小于0')
      }
    },
    // 提交表单
    submitForm() {
      // 检查是否有新项目
    if (this.projectList2.length === 0) {
        this.$message.warning('请至少添加一个新项目')
        return
    }
      let applicationDto = {
        applicationInfoDto: this.applicantInfo,
        customerDto: this.customerInfo,
        // 合并两个项目列表提交
        twoLists: [this.projectList1, this.projectList2]
      }
      
      this.$axios.post('api/project-server/application/addApplication', applicationDto)
        .then(resp => {
          console.log(resp)
          if(resp.data.code === 200) {
            // 提交成功后，将新项目移到已有项目列表中
            this.projectList1 = [...this.projectList1, ...this.projectList2.map(project => ({
              ...project,
              isNew: false
            }))]
            this.projectList2 = [] // 清空新项目列表
            this.$message.success('申请提交成功')
          }
        })
    },
    // 重置表单
    resetForm() {
      this.applicantInfo = {
        applicationName: '默认',
        applicationCode: '111111111111',
        applyDate: new Date()
      }
      this.customerInfo = {}
      this.projectList1 = []
      this.projectList2 = []
      this.$message.success('表单已重置')
    }
  }
}
</script>

<style scoped>
.project-application {
  padding: 20px;
}

.section-card {
  margin-bottom: 20px;
}

.customer-header,
.project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-item {
  margin-bottom: 20px;
}

.submit-section {
  text-align: center;
  margin-top: 30px;
}

.el-divider {
  margin: 24px 0;
}

.empty-project {
  text-align: center;
  padding: 40px 0;
}

.empty-project .el-empty {
  padding: 20px 0;
}
</style>
